<?php
// +----------------------------------------------------------------------
// | najing [ 通用后台管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.najingquan.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 救火队队长
// +----------------------------------------------------------------------

namespace  app\index\controller;

use app\BaseController;
use app\index\model\User as UserModel;
use app\index\model\UserLog;
use app\index\model\UserToken;
use think\facade\Db;
use think\facade\View;
use app\api\controller\EmailSend;
use think\facade\Cache;
use app\index\model\UserLog as userLogModel;

/**
 * 登陆管理
 * Class Login
 * @package app\admin\controller
 */
class Login extends  BaseController {

    /**
     * 登陆页
     * @author 救火队队长
     */
    public function  login() {
		if (Session('user')) {
            return redirect(url('home/index'));
        }
        session("user_pwd_change_name" , null);
        return View::fetch();
    }

    /**
     * 判断是否登陆
     * @author 救火队队长
     */
    public function checkLogin(){

        $data      = input('param.');
        $username   = trim($data['username']);
        $password   = trim($data['password']);

        if(empty($username) || empty($password)){
            return show(1,'邮箱和密码不为空.',[]);
        }
        $userInfo = Db::name('user')->where(['username' => $username])->find();
        if (!$userInfo) {
            return show(1,'用户不存在.',[]);
        }
        $user_id  = $userInfo['id'];
        $is_check = $userInfo['is_check'];
        if($is_check != 1){
            $token_list = Db::name('user_token')->field("distinct(ip) ip")->where(['user_id' => $user_id])->select()->toArray();
            $current_ip = ip();
            $ip_array   = [];
            //判断是否常用IP登录
            if($token_list){
                foreach ($token_list as $k=>$v){
                    $ip_array[] = $v['ip'];
                }
            }
            $is_email_check = getSetting('is_email_check');
            if($is_email_check != 1){
                if(!in_array($current_ip , $ip_array)){
                    return show(10,'非常用IP请用邮箱快捷登录.',[]);
                }
            }
        }
        $userInfo = Db::name('user')->where([
            'username' => $username,
            'password' => $this->enPassword($password, $userInfo['ctime'])
        ])->find();
        if ($userInfo) {
            $user_id        = $userInfo['id'];
            $user_status    = $userInfo['status'];
            if ($user_status == 1) {
                $userTokenModel = new UserToken();
                $user_token     = $userTokenModel->setToken(['user_id' => $userInfo['id']]);
                userLogModel::setLog($user_id , userLogModel::USER_LOGIN);
                session('user', $userInfo);
                session('user_token', $user_token);
                Db::name('user')
                    ->where(['id'=>$user_id])
                    ->update(['utime'=>getUtcTime()]);
                $url = url("home/index");
                $datas = [
                    'href' =>  $url->build(),
                ];
                return show(0,'登录成功.',$datas);
            }else if($user_status == 3){
                return show(1,'用户已注销.',[]);
            }else{
                return show(1,'用户已停用.',[]);
            }
        }else{
            return show(1,'密码错误，请重试.',[]);
        }
    }

    /**
     * 密码加密方法
     * @author 救火队队长
     */
    private function enPassword($password, $ctime)
    {
        return md5(md5($password) . $ctime);
    }

    public function checkLoginEmail(){
        $data      = input('param.');
        $email     = $data['email'];
        $vercode   = $data['vercode'];
        if(empty($email)) return json(['code'=>1,'msg'=>"邮箱不能为空."]);
        if(empty($vercode)) return json(['code'=>1,'msg'=>"验证码不能为空."]);

        $userInfo = Db::name('user')->where(['username' => $email])->find();
        if ($userInfo) {
            $key            = "{$email}_check_login_key";
            $cache_time     = Cache::store('redis')->get($key);
            if($vercode != $cache_time){
                return json(['code'=>1,'msg'=>"验证码错误."]);
            }

            $user_id        = $userInfo['id'];
            $user_status    = $userInfo['status'];
            if ($user_status == 1) {
                $userTokenModel = new UserToken();
                $user_token     = $userTokenModel->setToken(['user_id' => $userInfo['id']]);
                userLogModel::setLog($user_id , userLogModel::USER_LOGIN);
                session('user', $userInfo);
                session('user_token', $user_token);
                Db::name('user')
                    ->where(['id'=>$user_id])
                    ->update(['utime'=>getUtcTime()]);
                $url = url("home/index");
                $datas = [
                    'href' =>  $url->build(),
                ];
                return show(0,'登录成功.',$datas);
            }else if($user_status == 3){
                return show(1,'用户已注销.',[]);
            }else{
                return show(1,'用户已停用.',[]);
            }
        }else{
            return show(2,'用户未注册,请注册后再使用本平台.',[]);
        }
    }

    /**
     * 用户退出
     * @author 救火队队长
     */
    public function logout()
    {
        //增加退出日志
        if(session('user.id')){
            UserLog::setLog(session('user.id'),UserLog::USER_LOGOUT);
        }
        Session('user', null);
        Session('user_token', null);
        session('home_name', null);
        return redirect(url('index/'));
    }

    public function emailSend()
    {
        $username       = input('post.username');
        $send_type      = input('post.send_type');
        $check_email    = check_param($username , 'email');
        if(!$check_email) return json(['code'=>0,'msg'=>"邮箱格式不正确!"]);

        $user_list      = Db::name('user')->where([
            'username'  =>$username])->find();

        $user_status    = $user_list['status'];

        if($user_status == 2){
            return json(['code'=>0,'msg'=>"用户已停用!"]);
        }else if($user_status == 3){
            return json(['code'=>0,'msg'=>"用户已注销!"]);
        }

        if($send_type == 'check_zhuc'){
            if($user_list) return json(['code'=>0,'msg'=>"此邮箱已注册!"]);
        }else{
            if(empty($user_list)) return json(['code'=>0,'msg'=>"用户不存在."]);
        }

        $key            = "{$username}_{$send_type}_key";
        $cache_time     = Cache::store('redis')->get($key);

//        if(!empty($cache_time)){
//            return json(['code'=>0,'msg'=>"验证码有效期为3分钟,请查看邮箱获取."]);
//        }

        //获取随机6位字母
        $round_num     = nonceStr();
        //$send_type = check_login|check_pwd
        Cache::store('redis')->set($key, $round_num , 180);
        $result = EmailSend::sendGridEmail($send_type , [
            'email'     => $username,
            'code'      => $round_num
        ]);
        if($result){
            return json(['code'=>1,'msg'=>"验证码发送成功."]);
        }else{
            return json(['code'=>0,'msg'=>"验证码发送失败!"]);
        }
    }

    public function zhuc()
    {
        $getValue = getSetting('open_close_register');
        if($getValue == 1){
            return json(['code'=>0,'msg'=>"注册已关闭!"]);
        }

        try {
            $username           = trim(input('post.username'));
            $vercode            = trim(input('post.vercode'));
            $password           = trim(input('post.password'));
            $confirm_password   = trim(input('post.confirm_password'));
            $invitation_code    = trim(input('post.invitation_code'));
            $wx                 = input('post.wx' , '');
            $yqm                = input('post.yqm' , '');
            $l1                 = input('post.l1' , '');
            $l2                 = input('post.l2' , '');
            $invitation_code_sys= getSetting('user_invitation_code');
            if($invitation_code != $invitation_code_sys){
                return json(['code'=>0,'msg'=>"邀请码错误."]);
            }
            if(empty($username)) return json(['code'=>0,'msg'=>"邮箱不能为空."]);
            if(empty($vercode)) return json(['code'=>0,'msg'=>"验证码不能为空."]);
            if($l1 == 'false') return json(['code'=>0,'msg'=>"未同意隐私条款."]);
            if($l2 == 'false') return json(['code'=>0,'msg'=>"未同意平台使用规则."]);
            $key            = "{$username}_check_zhuc_key";
            $cache_time     = Cache::store('redis')->get($key);
            if($vercode != $cache_time){
                return json(['code'=>0,'msg'=>"验证码错误或已失效."]);
            }
            $user_list      = Db::name('user')->where([
                'username'  =>$username
            ])->find();
            if($user_list) return json(['code'=>0,'msg'=>"用户已存在."]);
            if(!check_param($username , 'email')) return json(['code'=>0,'msg'=>"邮箱格式错误."]);
            if(!check_param($password , 'password')) return json(['code'=>0,'msg'=>"密码必须为(12-32位,大小写字母,数字和特殊字符组合)."]);
            if($password != $confirm_password) return json(['code'=>0,'msg'=>"两次密码输入不一致."]);

            $ctime     = getUtcTime();
            //默认汇率
            $default_user_list = Db::name('user')->where(['id'=>1])->find();
            $usa_rate          = $default_user_list['usa_rate'] ?? 7.70;
            $dec_rate          = $default_user_list['dec_rate'] ?? 0;
            $re = Db::name('user')->save([
                'user_num'  => getRandNumber(),
                'username'  => $username,
                'password'  => md5(md5($password) . $ctime),
                'usa_rate'  => $usa_rate,
                'dec_rate'  => $dec_rate,
                'ctime'     => $ctime,
                'grade_new' => 2  //0=未认证,1=人脸认证,2=veriff未认证,3=veriff已认证
            ]);
            if($re){
                return json(['code'=>1,'msg'=>"注册成功."]);
            }else{
                return json(['code'=>0,'msg'=>"注册失败!"]);
            }
        }catch (\Exception $e){
            Db::name('api_error')->save([
                'user_id'       => 0,
                'amount'        => 0,
                'amount_bank'   => 0,
                'type'          => 'login_error',
                'data_param'    => $e->getMessage() . '---' . $e->getLine(),
                'ctime'         => getUtcTime()
            ]);
        }
    }


    public function resetPwd()
    {
        if($this->request->isPost()) {
            $username   = input('post.username');
            $vercode    = input('post.vercode');
            $current_time           = getUtcTime();
            $result = array(
                'code'   => 1,
                'msg'    => ''
            );

            $session_code       = \session("user_{$username}_check_pwd");
            $session_code_time  = \session("user_{$username}_check_pwd_time");
            if(($current_time - $session_code_time) >= 5*60){
                $result['code']   = 0; //验证码过期
                $result['msg']    = 'Captcha has expired.';
                return $result;
            }
            if($vercode != $session_code){
                $result['code']   = 0; //验证码过期
                $result['msg']      = 'Captcha error.';
                return $result;
            }
            session("user_pwd_change_name" , $username);
            session("user_{$username}_check_pwd" , null);
            session("user_{$username}_check_pwd_time" , null);
            return $result;
        }
        return View::fetch();
    }

    public function pwdChange()
    {
        if($this->request->isPost()) {
            $username           = trim(input('post.username'));
            $new_password       = trim(input('post.password'));
            $vercode            = trim(input('post.vercode'));
            $confirm_password   = trim(input('post.confirm_password'));
            if(empty($username)) return json(['code'=>0,'msg'=>"邮箱不能为空."]);
            if(empty($new_password)) return json(['code'=>0,'msg'=>"新密码不能为空."]);
            if(!check_param($new_password , 'password')) return json(['code'=>0,'msg'=>"密码必须为(大小写字母,数字和特殊字符组合12-36)."]);
            if($new_password != $confirm_password) return $this->err("两次密码不一致.");

            if(empty($vercode)) return json(['code'=>0,'msg'=>"验证码不能为空."]);
            $key            = "{$username}_check_pwd_key";
            $cache_time     = Cache::store('redis')->get($key);
            if($vercode != $cache_time) return json(['code'=>0,'msg'=>"验证码错误."]);

            $userModel  = new UserModel();
            $result     = $userModel->pwdChange($username,$new_password);
            if($result){
                return json(['code'=>1,'msg'=>"修改密码成功."]);
            }else{
                return json(['code'=>0,'msg'=>"修改密码失败."]);
            }
        }

        return View::fetch();
    }
}
